package com.nami.gate.utils;

import com.nami.gate.config.CommandConfig;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class YamlReader {

    private Map<String, Object> yamlData;

    public YamlReader(CommandConfig config) throws IOException {
        // 创建一个 YAML 解析器
        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            if (!config.getIsDefaultPath()) {
                inputStream = new FileInputStream(config.getFilePath());
            } else {
                inputStream = getClass().getClassLoader().getResourceAsStream(config.getFilePath());
            }

            // 通过输入流加载 YAML 文件
            if (inputStream != null) {
                yamlData = yaml.load(inputStream);
                return;
            }
            throw new IllegalArgumentException("YAML file not found.");
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    // 获取值
    public Object getValue(String key) {
        String[] keys = key.split("\\.");  // 分割点来处理嵌套结构
        return getNestedValue(yamlData, keys, 0);
    }

    public String getStrValue(String key) {
        Object value = getValue(key);
        return value == null ? "" : value.toString();
    }

    public Integer getIntegerValue(String key) {
        Object value = getValue(key);
        return value == null ? null : (Integer) value;
    }


    private Object getNestedValue(Map<String, Object> currentMap, String[] keys, int index) {
        if (index == keys.length) {
            return currentMap;
        }
        Object next = currentMap.get(keys[index]);
        if (next instanceof Map) {
            return getNestedValue((Map<String, Object>) next, keys, index + 1);
        } else {
            return next;
        }
    }

//    public static void main(String[] args) throws IOException {
//        YamlReader reader = new YamlReader(null);
//        String key1 = "netty.port";
//        String key2 = "y.b.c";
//
//        // 获取值并输出
//        System.out.println("Value for '" + key1 + "': " + reader.getValue(key1));
//        System.out.println("Value for '" + key2 + "': " + reader.getValue(key2));
//    }
}
